//
//  ComposeViewController.swift
//  VVbo
//
//  Created by Mr.Run on 2017/9/6.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    @IBOutlet weak var toolbar: UIToolbar!
    
    @IBOutlet weak var textView: ComposeTextView!
    
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func keyboardChanged(n: Notification) {
        
//        UIKeyboardFrameEndUserInfoKey
        
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
            else {
                return
        }
        
        let offset = view.bounds.height - rect.origin.y
        
        toolbarBottomCons.constant = offset
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func postStatus() {
        guard let text = textView.text else {
            return
        }
        print(emoticonText)
//        NetworkManager.shared().postStatus(text: text) { (result, isSuccess) in
//            print(result ?? [])
//        }
        
    }
    
    var emoticonText:String{
        
        guard let attrStr = textView.attributedText else{
            return ""
        }
        var result = String()
        attrStr.enumerateAttributes(in: NSRange(location: 0, length: attrStr.length), options: []) { (dict, range, _) in
            if let attatchment = dict["NSAttachment"] as? EmoticonAttachment{
                result += attatchment.chs ?? ""
            }else{
                let subStr = (attrStr.string as NSString).substring(with: range)
                result += subStr
            }
        }
        
        return attrStr.string
    }
    
    @objc fileprivate func emoticonKeyboard() {
        
        
        let keyboardView = EmoticonInputView.inputView {[weak self] (em) in
            self?.insertEmoticon(em: em)
        }
        keyboardView.backgroundColor = UIColor.white
        textView.inputView = (textView.inputView == nil) ? keyboardView : nil
        textView.becomeFirstResponder()
        textView.reloadInputViews()
        
    }
    
    func insertEmoticon(em:Emoticon?) {
        guard let em = em else{
            
            textView.deleteBackward()
            return
        }
        
        if let emoji = em.emoji, let textRange = textView.selectedTextRange {
            textView.replace(textRange, withText: emoji)
            return
        }
//        let imageText = NSMutableAttributedString(attributedString: em.imageText(font: textView.font!))
//        imageText.addAttributes([NSFontAttributeName: textView.font!], range: NSRange(location: 0, length: 1))
        
        let imageText = em.imageText(font: textView.font!)
        
        let attrStrM = NSMutableAttributedString(attributedString: textView.attributedText)
        attrStrM.replaceCharacters(in: textView.selectedRange, with: imageText)
        let range = textView.selectedRange
        textView.attributedText = attrStrM
        textView.selectedRange = NSRange(location: range.location+1, length: 0)
        textView.delegate?.textViewDidChange?(textView)
        
    }
    
    lazy var sendBtn:UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("发布", for: [])
        btn.addTarget(self, action: #selector(postStatus), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.white, for: [])
        btn.setTitleColor(UIColor.gray, for: .disabled)
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), for: [])
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named:"common_button_white"), for: .disabled)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
        return btn
    }()
    
}

extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: ComposeTextView) {
        sendBtn.isEnabled = textView.hasText
        textView.placeholderLabel.isHidden = textView.hasText
        
    }
    
}

fileprivate extension ComposeViewController {
    
    func setupUI() {
        view.backgroundColor = UIColor.white
        setupNavigationBar()
        setupToolbar()
    }
    
    func setupToolbar() {
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            guard let imageName = s["imageName"] else{
                continue
            }
            let image = UIImage(named:imageName)
            let imageNameHL = imageName.appending("_highlighted")
            let imageHL = UIImage(named:imageNameHL)
            let btn = UIButton()
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            btn.sizeToFit()
            
            if let actionName = s["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            items.append(UIBarButtonItem(customView: btn))
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        
    }
    
}

